import OpenAI from 'openai'
import { OpenAIStream, StreamingTextResponse } from 'ai'

const client = new OpenAI({
    apiKey: process.env.KIMI_API_KEY as string,
    baseURL: 'https://api.moonshot.cn/v1'
})

export const runtime = 'edge'

export async function POST(req: Request) {
    const model = 'moonshot-v1-8k'
    const { messages } = await req.json()
    const response = await client.chat.completions.create({
        model,
        stream: true,
        messages,
        temperature: 0.8
    })
    const stream = OpenAIStream(response, {
        onStart: async () => {
            // This callback is called when the stream starts
            // You can use this to save the prompt to your database
            // await savePromptToDatabase(prompt);
        },

        onToken: async (token: string) => {
            // This callback is called for each token in the stream
            // You can use this to debug the stream or save the tokens to your database
            // console.log('token: ', token)
        },

        onCompletion: async (completion: string) => {
            // This callback is called when the stream completes
            // You can use this to save the final completion to your database
            // await saveCompletionToDatabase(completion);
        }
    })
    return new StreamingTextResponse(stream)
}